/* COPYRIGHT_CHUNFENG */
#include "cf_log.h"
#include "cf_std.h"
#include "unistd.h"
static FILE *cf_log_error_file_fp = NULL;
static int error_log_lock = 0;
static FILE *cf_log_debug_file_fp = NULL;
static int debug_log_lock = 0;
static FILE *cf_log_message_file_fp = NULL;
static int message_log_lock = 0;


int cf_log_file(enum CF_LOG_TYPE type, const char* file_path, const char* format, ...)
{
	FILE* *cf_log_file_fp;
	int * lock;
	va_list va;
	int i = 0;
	switch(type)
	{
		case LOG_MESSAGE:
			lock = &message_log_lock;
			cf_log_file_fp = &cf_log_message_file_fp;
			break;
		case LOG_ERROR:
			lock = &error_log_lock;
			cf_log_file_fp = &cf_log_error_file_fp;
			break;
		case LOG_DEBUG:
			lock = &debug_log_lock;
			cf_log_file_fp = &cf_log_debug_file_fp;
			break;
	}
	
	while(*lock){
		i++;
		usleep(10000);
		if(i == 1000) break;
	}
	*lock = 1;
	
	if(!*cf_log_file_fp)
	{
		*cf_log_file_fp = fopen(file_path, "a+b");
		if(!*cf_log_file_fp){
			*lock = 0;
			return -1;
		}
	}
	va_start(va, format);
	vfprintf(*cf_log_file_fp, format, va);
	fflush(*cf_log_file_fp);
	va_end(va);
	*lock = 0;
	return 0;
}

int cf_log_close_file()
{
	int res = 0;
	if(cf_log_debug_file_fp) res += fclose(cf_log_debug_file_fp);
	if(cf_log_error_file_fp) res += fclose(cf_log_error_file_fp);
	if(cf_log_message_file_fp) res += fclose(cf_log_message_file_fp);
	return res;
}